package com.gui.juc.cas;

import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class CASArrayDemo {

    public static void main(String[] args) {

        test(
                () -> new int[10],
                array -> array.length,
                (array, i) -> array[i] += 1,
                array -> log.debug(Arrays.toString(array))
        );

        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(10);
        test(
                () -> atomicIntegerArray,
                AtomicIntegerArray::length,
                AtomicIntegerArray::incrementAndGet,
                array -> log.debug("最终打印结果为：{}", array)

        );


    }

    private static <T, R extends Integer> void test(Supplier<T> supplier, Function<T, R> function, BiConsumer<T, Integer> consumer, Consumer<T> print) {
        T array = supplier.get();
        Integer length = function.apply(array);
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        for (int j = 0; j < 4; j++) {
            threadPool.submit(() -> {
                for (int k = 0; k < 1000000; k++) {
                    for (int i = 0; i < length; i++) {
                        consumer.accept(array, i);
                    }
                }
            });
        }

        threadPool.shutdown();
        Sleeper.sleep(5);

        print.accept(array);

    }

}
